package com.ztesoft.report.controller;

import com.alibaba.fastjson.JSON;
import com.ztesoft.report.base.controller.BaseController;
import com.ztesoft.report.base.pojo.R;
import com.ztesoft.report.engine.options.QueryParameterOptions;
import com.ztesoft.report.engine.util.VelocityUtils;
import com.ztesoft.report.entity.ReportDto;
import com.ztesoft.report.service.ReportService;
import com.ztesoft.report.service.TableReportService;
import com.ztesoft.report.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author y3tu
 * @date 2018/5/30
 */
@RestController
@RequestMapping(value = "/designer")
@Slf4j
public class DesignerController extends BaseController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private TableReportService tableReportService;

    /**
     * 获取报表元数据列集合
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/execSqlText")
    public R execSqlText(@RequestBody Map paramMap, final HttpServletRequest request) {

        Integer dsId = Integer.valueOf(paramMap.get("dsId").toString());
        String sqlText = paramMap.get("sqlText").toString();
        String queryParams = filterNull(paramMap, "queryParams").toString();
        if (dsId != null) {
            sqlText = this.getSqlText(sqlText, queryParams, request);
            return R.ok(this.reportService.getMetaDataColumns(dsId, sqlText));
        }
        return R.error("没有选择数据源");
    }

    @PostMapping(value = "/add")
    public Map add(@RequestBody ReportDto po) {
        po.setCreateUser(getCurrentUser());
        po.setUpdateUser(getCurrentUser());
        Map  map = null;
        try {
            map = reportService.addReport(po);
        }catch (Exception e) {
            log.error("", e);
            return R.error("新增失败，请联系相关工作人员");
        }
        return map;
    }

    @PostMapping(value = "/update")
    public Map update(@RequestBody ReportDto po) {
        po.setUpdateUser(getCurrentUser());
        po.setUpdateTime(new Date());
        Map  map = null;
        try {
            map = reportService.updateReport(po);
        } catch (NullPointerException e) {
            map = R.error("修改失败，选择的报表包含未处理完成数据，不能修改！");
        } catch (Exception e) {
            log.error("", e);
            return R.error("新增失败，请联系相关工作人员");
        }
        return map;
    }

    @RequestMapping(value = "/previewReport")
    public Map previewReport(@RequestBody ReportDto po) {
        Map  map = null;
        try {
            map = reportService.previewReport(po);
        } catch (Exception e) {
            log.error("", e);
            return R.error("预览失败，请联系相关工作人员");
        }
        return map;
    }

    /**
     * 拼装sql
     *
     * @param sqlText
     * @param queryParams
     * @param request
     * @return
     */
    private String getSqlText(final String sqlText, final String queryParams, final HttpServletRequest request) {
        final Map<String, Object> formParameters =
                this.tableReportService.getBuildInParameters(request.getParameterMap());
        if (StringUtils.isNotBlank(queryParams)) {
            final List<QueryParameterOptions> queryParameters = JSON.parseArray(queryParams,
                    QueryParameterOptions.class);
            queryParameters.stream()
                    .filter(parameter -> !formParameters.containsKey(parameter.getName()))
                    .forEach(parameter -> formParameters.put(parameter.getName(), parameter.getRealDefaultValue()));
        }
        return VelocityUtils.parse(sqlText, formParameters);
    }


}
